package GUI.LessonMouse;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Iterator;

//鼠标监听事件
public class TextMouseListener {
    public static void main(String[] args) {
        new MyFrame("画图");
    }
}

class MyFrame extends Frame {
    //画画需要画笔，需要监听鼠标当前的位置，需要集合来储存这个点
    ArrayList points;
    public MyFrame(String title) {
        super(title);
        setBounds(500,250,400,400);
        setBackground(Color.YELLOW);
        points = new ArrayList();       //存放鼠标点击的点
        addMouseListener(new MyMouseListener());     //鼠标监听器
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        setVisible(true);
    }
    @Override
    public void paint(Graphics g) {
        //画画，监听鼠标的事件
        Iterator iterator = points.iterator();
        while(iterator.hasNext()) {
            Point point =(Point)iterator.next();
            g.setColor(Color.GREEN);
            g.fillOval(point.x,point.y,10,10);
        }
    }
    public void addPoint(Point point) {
        points.add(point);
    }
    private class MyMouseListener extends MouseAdapter {
        //鼠标 按下，弹起，按住不放
        @Override
        public void mousePressed(MouseEvent e) {
            MyFrame frame = (MyFrame) e.getSource();
            frame.addPoint(new Point(e.getX(),e.getY()));          //画的点就是鼠标的点
            //每次点击鼠标都要重新画一遍
            frame.repaint();
        }
    }
}
